#include "relay_ctrl.h"
#include "relay.h"
#include "systime.h"

#define relay_pluse_width	20 //磁保持继电器脉冲宽度，单位ms

typedef enum
{
	STATE_DET,
	STATE_ON_START,
	STATE_ON_END,
	STATE_OFF_START,
	STATE_OFF_END,
	
}RELAY_CTRL_STATE;

static struct
{
	RELAY_CTRL_STATE 			state;
	uint8_t						update_flag;
	relay_state_e     				g_sw;
	timestamp_t						time;

}relay_ctrl;

void relay_ctrl_init(void)
{
	relay_init();
	
	relay_ctrl.state = STATE_DET;
	relay_ctrl.g_sw = RELAY_OFF;
	relay_ctrl.update_flag = FALSE;
}


void set_relay_sw(relay_state_e sw)
{
	if(!relay_ctrl.update_flag){
		relay_ctrl.g_sw = sw;
		relay_ctrl.update_flag = TRUE;
	}

}


void relay_ctrl_task(void)
{
	switch(relay_ctrl.state){
		case STATE_DET:
			if(relay_ctrl.update_flag){
				if(relay_ctrl.g_sw == RELAY_ON){
					relay_ctrl.state = STATE_ON_START;
				}else{
					relay_ctrl.state = STATE_OFF_START;
				}
			}
			break;
		case STATE_ON_START:
			set_relay_on_pin_state(HIGH);
			relative_time_add_ms(&relay_ctrl.time, relay_pluse_width);
			relay_ctrl.state = STATE_ON_END;
			break;
		case STATE_ON_END:
			if(is_relative_time_timeout(&relay_ctrl.time)){
				set_relay_on_pin_state(LOW);
				relay_ctrl.update_flag = FALSE;
				relay_ctrl.state = STATE_DET;
			}
			break;
		case STATE_OFF_START:
			set_relay_off_pin_state(HIGH);
			relative_time_add_ms(&relay_ctrl.time, relay_pluse_width);
			relay_ctrl.state = STATE_OFF_END;
			break;
		case STATE_OFF_END:
			if(is_relative_time_timeout(&relay_ctrl.time)){
				set_relay_off_pin_state(LOW);
				relay_ctrl.update_flag = FALSE;
				relay_ctrl.state = STATE_DET;
			}
			break;
		default:
			set_relay_on_pin_state(LOW);
			set_relay_off_pin_state(LOW);
			relay_ctrl.update_flag = FALSE;
			relay_ctrl.state = STATE_DET;
			break;
	
	}
}


relay_state_e  get_relay_sw(void)
{
    return relay_ctrl.g_sw;
}

